package com.mooc.apigateway.dao;

import com.google.common.collect.Lists;
import com.mooc.apigateway.common.RestResponse;
import com.mooc.apigateway.common.page.PageParams;
import com.mooc.apigateway.config.GenericRest;
import com.mooc.apigateway.model.Agency;
import com.mooc.apigateway.model.ListResponse;
import com.mooc.apigateway.model.User;
import com.mooc.apigateway.model.UserMsg;
import com.mooc.apigateway.utils.Rests;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
@Repository
@DefaultProperties(groupKey="userDao",
        commandProperties={@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000")},
        threadPoolProperties={@HystrixProperty(name="coreSize",value="10")
                ,@HystrixProperty(name="maxQueueSize",value="1000")},
        threadPoolKey="userDao"
)
public class UserDao {

    @Autowired
    private GenericRest rest;
    @Value("${user.service.name}")
    private String userServiceName;

    public String test(){
        String url = Rests.toUrl(userServiceName, "/user/test");
        RestResponse<String> response = rest.get(url,
                new ParameterizedTypeReference<RestResponse<String>>() {
                }).getBody();
        return response.getResult();
    }

    public String getusername(Long id){
        //String url = "direct://http://localhost:8083/user/getusername?id="+id;
       // String url = "http://user/user/ugetusername?id="+id;
        String url = Rests.toUrl(userServiceName, "/user/getusername?id=7");
        RestResponse<String> response = rest.get(url,
                new ParameterizedTypeReference<RestResponse<String>>() {
        }).getBody();
        return response.getResult();
    }

    public List<Agency> getNullAgency(){
        return new ArrayList();
    }

    @HystrixCommand(fallbackMethod = "getNullAgency")
    public List<Agency> getAllAgency(){
       return Rests.exc(() ->{
            String url = Rests.toUrl(userServiceName, "/agency/list");
            ResponseEntity<RestResponse<List<Agency>>>  responseEntity =
                   rest.get(url, new ParameterizedTypeReference<RestResponse<List<Agency>>>() { });
           return responseEntity.getBody();
       }).getResult();

    }

    public User updateUser(User user){
        return Rests.exc(() ->{
            String url = Rests.toUrl(userServiceName,"user/update");
            ResponseEntity<RestResponse<User>> responseEntity = rest.post(url, user, new ParameterizedTypeReference<RestResponse<User>>() {});
            return responseEntity.getBody();
        }).getResult();

        }




    public List<User> getUserList(User query) {
        ResponseEntity<RestResponse<List<User>>> resultEntity = rest.post("http://" + userServiceName + "/user/getList", query,
                new ParameterizedTypeReference<RestResponse<List<User>>>() {
                });
        RestResponse<List<User>> restResponse = resultEntity.getBody();
       if(restResponse.getCode() == 0){
           return restResponse.getResult();
       }
       return Lists.newArrayList();
    }

    public User addUser(User account) {
        String url = "http://" + userServiceName + "/user/add";
        ResponseEntity<RestResponse<User>> responseEntity = rest.post(url, account, new ParameterizedTypeReference<RestResponse<User>>() {
        });
        RestResponse<User> restResponse = responseEntity.getBody();
        if(restResponse.getCode() == 0){
            return restResponse.getResult();
        }
        return null;
    }

    public boolean enable(String key){
        String url = "http://" + userServiceName + "/user/enable?key=" + key;
        RestResponse<Object> response = rest.get(url, new ParameterizedTypeReference<RestResponse<Object>>() {
        }).getBody();
        return response.getCode() == 0;
    }


    public User authUser(User user) {
        String url = "http://" + userServiceName + "/user/auth";
        ResponseEntity<RestResponse<User>> responseEntity = rest.post(url, user, new ParameterizedTypeReference<RestResponse<User>>() {});
        RestResponse<User> response = responseEntity.getBody();
        if(response.getCode() != 0){
           throw new IllegalStateException("Can not auth user");
        }
        return response.getResult();

    }


    public void logout(String token) {
        String url = "http://" + userServiceName
                + "/user/logout?token=" + token;
        rest.get(url, new ParameterizedTypeReference<Object>() {
        });
    }

    public User getUserByTokenFb(String token){
        return new User();
    }

    //服务调用失败后会调用fallbackMethod这个方法,参数要一致
    @HystrixCommand(fallbackMethod = "getUserByTokenFb")
    public User getUserByToken(String token) {
      String url = "http://" + userServiceName +
              "/user/get?token=" + token;
        ResponseEntity<RestResponse<User>> responseEntity = rest.get(url, new ParameterizedTypeReference<RestResponse<User>>() {
        });
        RestResponse<User> response = responseEntity.getBody();
        if(response == null || response.getCode() != 0){
            return null;
        }
        return response.getResult();
    }

    public User getAgentById(Long id) {
        User result = Rests.exc(() -> {
            String url = Rests.toUrl(userServiceName, "/agency/agentDetail?id=" + id);
            ResponseEntity<RestResponse<User>> responseEntity = rest.get(url, new ParameterizedTypeReference<RestResponse<User>>() {
            });
            return responseEntity.getBody();
        }).getResult();
        return result;
    }


    public void sendUserMail(UserMsg userMsg) {

        Rests.exc(() -> {
            String url = Rests.toUrl(userServiceName, "/agency/sendUserMail");
            ResponseEntity<RestResponse> responseEntity = rest.post(url, userMsg,
                    new ParameterizedTypeReference<RestResponse>() {
                    });
            return responseEntity.getBody();
        });

    }


    public ListResponse<User> getAgentList(PageParams pageParams) {

        RestResponse<ListResponse<User>> exc = Rests.exc(() -> {
            String url = Rests.toUrl(userServiceName, "/agency/agentList");
            ResponseEntity<RestResponse<ListResponse<User>>> responseEntity = rest.post(url, pageParams,
                    new ParameterizedTypeReference<RestResponse<ListResponse<User>>>() {
                    });
            return responseEntity.getBody();
        });
        return exc.getResult();
  }

}
